﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Home.Haushalt.Lib;
using Home.Haushalt.Lib.Element;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using System.Linq;

namespace Home.Haushalt.Gui
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UcGridFormMonthbalance : UcGridForm
    {
        /// <summary></summary>
        private Monthbalance _monthbalance;

        /// <summary></summary>
        private string _termin { get { return _monthbalance.Year.ToString() + _monthbalance.Month.ToString("00"); } }

        /// <summary></summary>
        private bool _activeOnly = false;

        /// <summary>
        /// 
        /// </summary>
        public UcGridFormMonthbalance()
            : this(DateTime.Now.Month, DateTime.Now.Year) { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="month"></param>
        /// <param name="year"></param>
        public UcGridFormMonthbalance(int month, int year)
            : base(DefaultColumnSets.GridDefault, DefaultColumnSets.GridDefault.ToString())
        {
            InitializeComponent();

            BaseGrid.OnElementDeleted += new EventHandler<HEventArgs>(BaseGrid_OnElementChanged);
            BaseGrid.OnElementChanged += new EventHandler<HEventArgs>(BaseGrid_OnElementChanged);
            BaseGrid.OnSelect += new EventHandler<HEventArgs>(BaseGrid_OnSelect);
            BaseGrid.DisplayLayout.Override.HeaderClickAction = HeaderClickAction.Select;
            BaseGrid.DisplayLayout.Override.AllowRowFiltering = DefaultableBoolean.False;

            BaseGrid.ContextMenuStrip.Opened += new EventHandler(ContextMenuStrip_Opened);

            lblSelectSum.Text = "";

            _monthbalance = DAO.MonthbalanceCollection.Add(month, year);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmGridForm_Load(object sender, EventArgs e)
        {
            if (!LayoutController.IsInDesignMode(this))
            {
                DataBind(true);

                WindowController.RefreshMonthbalanceGrids();
            }
        }

        #region BINDING

        /// <summary>
        /// 
        /// </summary>
        /// <param name="activeOnly"></param>
        private void DataBind(bool activeOnly)
        {
            _activeOnly = activeOnly;

            cbMonth.DataSource = DAO.MonthnamesTable;
            cbMonth.DisplayMember = DAO.COLUMNNAME_MONTHNAME_NAME;
            cbMonth.ValueMember = DAO.COLUMNNAME_MONTHNAME_NUMBER;
            cbMonth.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            cbMonth.DisplayLayout.Bands[0].ColHeadersVisible = false;

            foreach (UltraGridRow row in cbMonth.Rows)
            {
                if (row.Cells[DAO.COLUMNNAME_MONTHNAME_NUMBER].Value.ToInt() == _monthbalance.Month)
                {
                    row.Selected = true;
                    break;
                }
            }

            txtYear.Text = _monthbalance.Year.ToString();

            RefreshDataBinding();
        }

        /// <summary>
        /// 
        /// </summary>
        public void RefreshDataBinding()
        {
            txtSaldo.Text = _monthbalance.StartSaldo.ToString("c");

            BaseGrid.DataBind(Date.ElementType, DefaultColumnSets.balance);

            FilterBind();
        }

        /// <summary>
        /// 
        /// </summary>
        public void WindowControllerUpdate()
        {
            txtSaldo.Text = _monthbalance.StartSaldo.ToString("c");

            BaseGrid.DataBind(Date.ElementType, DefaultColumnSets.balance);
            
            FilterBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="activeOnly"></param>
        public void FilterBind(bool activeOnly)
        {
            _activeOnly = activeOnly;

            FilterBind();
        }

        /// <summary>
        /// 
        /// </summary>
        private void FilterBind()
        {
            UltraGridBand band = BaseGrid.DisplayLayout.Bands[0];
            band.SortedColumns.Clear();
            band.SortedColumns.Add(band.Columns[Date.Fields.Posting], false);
            band.SortedColumns.Add(band.Columns[Date.Fields.OpponentId], false);
            band.SortedColumns.Add(band.Columns[Date.Fields.SaldotypId], true);
            band.SortedColumns.Add(band.Columns[Date.Fields.Summe], true);

            ColumnFilter terminFilter = band.ColumnFilters[Date.Fields.Posting];
            ColumnFilter activeFilter = band.ColumnFilters[Date.Fields.Active];

            terminFilter.FilterConditions.Clear();
            terminFilter.FilterConditions.Add(new FilterCondition(FilterComparisionOperator.GreaterThanOrEqualTo, _monthbalance.FromDate));
            terminFilter.FilterConditions.Add(new FilterCondition(FilterComparisionOperator.LessThanOrEqualTo, _monthbalance.ToDate));
            terminFilter.LogicalOperator = FilterLogicalOperator.And;


            activeFilter.FilterConditions.Clear();
            if (_activeOnly)
            {
                activeFilter.FilterConditions.Add(new FilterCondition(FilterComparisionOperator.Equals, true));
            }

            BaseGrid.ActiveRow = null;

            //BaseGrid.CalculateUnboundFields();
            BaseGrid.InitializeRowsAppearances();

            //Balanz-Spalte dezenter
            foreach (UltraGridRow row in BaseGrid.Rows)
            {
                //row.Cells[Date.Fields.UnboundSaldo].Appearance.ForeColor = row.Cells[Date.Fields.UnboundSaldo].Value.ToInt() < 0 ? Color.MistyRose : Color.Green;
                row.Cells[Date.Fields.Saldo].Appearance.ForeColor = Color.Gray;
                row.Cells[Date.Fields.Saldo].Appearance.ForegroundAlpha = Alpha.UseAlphaLevel;
                row.Cells[Date.Fields.Saldo].Appearance.AlphaLevel = (short)DAO.Settings.Selected.MonthbalanceGridSaldoAlpha;
            }
        }

        #endregion BINDING

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ContextMenuStrip_Opened(object sender, EventArgs e)
        {
            if (BaseGrid._clickedObject is UltraGridCell || BaseGrid._clickedObject is UltraGrid)
            {
                int insertIndex = 3;
                ToolStripSeparator separator = new ToolStripSeparator();
                BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, separator);

                ToolStripMenuItem checked1 = new ToolStripMenuItem(LO.GridContextMenu("Element.Date.CheckToday", DateTime.Now.ToString("(dd.MM.yy)")), global:: Home.Haushalt.Lib.Properties.Resources.ok2, checkAtToday);
                checked1.Enabled = (BaseGrid.Selected.Rows.Count > 0);
                BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, checked1);

                ToolStripMenuItem checked2 = new ToolStripMenuItem(LO.GridContextMenu("Element.Date.CheckYesterday", DateTime.Now.AddDays(-1).ToString("(dd.MM.yy)")), global:: Home.Haushalt.Lib.Properties.Resources.ok2, checkAtYesterday);
                checked2.Enabled = (BaseGrid.Selected.Rows.Count > 0);
                BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, checked2);

                ToolStripMenuItem checked3 = new ToolStripMenuItem(LO.GridContextMenu("Element.Date.Uncheck"), null, Uncheck);
                checked3.Enabled = (BaseGrid.Selected.Rows.Count > 0);
                BaseGrid.ContextMenuStrip.Items.Insert(insertIndex++, checked3);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkAtToday(object sender, EventArgs e)
        {
            CheckAtDate(DateTime.Now);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkAtYesterday(object sender, EventArgs e)
        {
            CheckAtDate(DateTime.Now.AddDays(-1));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        private void CheckAtDate(DateTime date)
        {
            foreach (DataRow selectedRow in BaseGrid.Selected.Rows.Cast<UltraGridRow>().Select(item => item.ToDataRow()))
            {
                selectedRow[Date.Fields.Posting] = date;
                selectedRow[Date.Fields.Active] = false;
            }

            BaseGrid.CellUpdate(BaseGrid.Selected.Rows.Cast<UltraGridRow>().Select(item => item.ToDataRow()).ToArray());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Uncheck(object sender, EventArgs e)
        {
            foreach (DataRow selectedRow in BaseGrid.Selected.Rows.Cast<UltraGridRow>().Select(item => item.ToDataRow()))
            {
                selectedRow[Date.Fields.Active] = true;
            }

            BaseGrid.CellUpdate(BaseGrid.SelectedRows.Select(item => item.ToDataRow()).ToArray());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_OnSelect(object sender, HEventArgs e)
        {
            if (BaseGrid.SelectedRows.Count > 1)
            {
                double summe = 0;
                foreach (UltraGridRow ultrarow in BaseGrid.SelectedRows)
                {
                    DataRow row = ultrarow.ToDataRow();

                    double value = row[Date.Fields.Summe].ToDouble() * row[Date.Fields.SaldotypId].ToInt();
                    summe += (value);

                }

                lblSelectSum.Text = summe.ToString("c2") + " /";
            }
            else
            {
                lblSelectSum.Text = "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BaseGrid_OnElementChanged(object sender, HEventArgs e)
        {
            DAO.MonthbalanceCollection.DataBind();

            //Sonst addiert es sich mit dem letzten Wert angefangen
            // BalanceCtrl.CalculateScheduledSaldoTempField = BalanceCtrl.StartSaldo;

            //WindowController.RefreshMonthbalanceGrids();
            //DataBind(_year, _month, _activeOnly);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            if (BaseGrid.Selected.Rows.Count > 0)
            {
                BaseGrid.EditElementProperty(BaseGrid.Selected.Rows[0].ToDataRow());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbActiveOnly_CheckStateChanged(object sender, EventArgs e)
        {
            FilterBind(cbActiveOnly.CheckState == CheckState.Checked);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextMonth_Click(object sender, EventArgs e)
        {
            DateTime currentDate = new DateTime(txtYear.Text.ToInt(), cbMonth.SelectedRow.Cells[DAO.COLUMNNAME_MONTHNAME_NUMBER].Value.ToInt(), 1);
            DateTime newDate = currentDate.AddMonths((sender == btnNextMonth) ? 1 : -1);

            UcGridFormMonthbalance ucGridForm = new UcGridFormMonthbalance(newDate.Month, newDate.Year);

            FrmGridForm frmGridForm = new FrmGridForm(ucGridForm);

            frmGridForm.Show();
            frmGridForm.Top = WindowController.FistGridForm.Top + 20;
            frmGridForm.Left = WindowController.FistGridForm.Left + 20;

        }
    }
}
